<?php

if (! function_exists('bcrypt')) {
    /**
     * Hash the given value.
     *
     * @param  string  $value
     * @param  array   $options
     * @return string
     */
    function bcrypt($value, $options = [])
    {
        return app('hash')->make($value, $options);
    }
}

if (! function_exists('parseIdsString')) {
    /**
     * @param  string  $value
     * @return array
     */
    function parseIdsString($value)
    {
        $result = [];
        if ($value && $explode = array_map('intval', str_getcsv($value))) {
            $result = array_values(array_unique(array_filter($explode)));
        }
        return $result;
    }
}

if (! function_exists('parseRangeString')) {
    /**
     * @param  string  $value
     * @param  string  $format eg. intval/floatval/trim
     * @param  string  $explodeChar eg. [~ , -]
     * @return array
     */
    function parseRangeString($value, $format = 'intval', $explodeChar = '~')
    {
        $result = [];
        $value = str_replace(' ', null, trim($value));
        if ($value && $explode = explode($explodeChar, $value)) {
            $slice = array_slice($explode, 0, 2);
            if (count($slice) !== 2) {
                return [];
            }
            if (strlen($slice[0]) > 0) {
                $result['gte'] = $format($slice[0]);
            }
            if (strlen($slice[1]) > 0 && $slice[1] >= $slice[0]) {
                $result['lte'] = $format($slice[1]);
            }
        }
        return $result;
    }
}

if (! function_exists('parseSortString')) {
    /**
     * @param $value
     * @return array
     */
    function parseSortString($value)
    {
        $result = [];
        if ($value) {
            $explode = array_filter(array_map('trim', explode(',', $value)));
            foreach ($explode as $item) {
                $firstChar = substr($item, 0, 1);
                $remainPart = substr($item, 1);
                if ($firstChar == '+') {
                    $result[$remainPart] = 'asc';
                }
                if ($firstChar == '-') {
                    $result[$remainPart] = 'desc';
                }
            }
        }
        return $result;
    }
}

if (!function_exists('getConstantsFromClass')) {
    /**
     * @param $className
     * @param $prefix
     * @return array
     */
    function getConstantsFromClass($className, $prefix = null)
    {
        $constants = (new \ReflectionClass($className))->getConstants();
        if (!empty($prefix)) {
            return array_filter($constants, function ($key) use ($prefix) {
                return strpos($key, $prefix) === 0;
            }, ARRAY_FILTER_USE_KEY);
        }

        return $constants;
    }
}

if (!function_exists('encryptPassword')) {
    /**
     * @param $password
     * @param string $datetime 创建时间(Y-m-d H:i:s)
     * @return string
     */
    function encryptPassword($password, $datetime)
    {
        return md5($password .'@'. $datetime);
    }


    if (! function_exists('config_path')) {
        /**
         * Get the configuration path.
         *
         * @param  string  $patha
         * @return string
         */
        function config_path($path = '')
        {
            return app()->basePath() . DIRECTORY_SEPARATOR . 'config'.($path ? DIRECTORY_SEPARATOR.$path : $path);
        }
    }

    if (! function_exists('sunmi_post')) {
        /**
         * @param $url
         * @param null $data
         * @param null $headers
         * @return mixed
         */
        function sunmi_post($url, $data=null, $headers=null){
            $ch = curl_init($url);
            if(!empty($headers)){
                $headerArr = array();
                foreach( $headers as $n => $v ) {
                    $headerArr[] = $n .':' . $v;
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
            }
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
            if(!empty($data)){
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
            $ret =  curl_exec($ch);//运行curl
            curl_close($ch);
            $res = json_decode($ret, true);
            return $res;
        }
    }

    if (! function_exists('sunmi_get')) {
        function sunmi_get($url, $data=null, $headers=null){
            if(!empty($data)){
                $url .= '?' . http_build_query($data);
            }
            $ch = curl_init($url);
            if(!empty($headers)){
                $headerArr = array();
                foreach( $headers as $n => $v ) {
                    $headerArr[] = $n .':' . $v;
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
            $res =  curl_exec($ch);//运行curl
            curl_close($ch);
            return json_decode($res);
        }
    }

    if (! function_exists('teambition_get')) {
        function teambition_get($url, $data=null, $headers=null){
            if(!empty($data)){
                $url .= '?' . http_build_query($data);
            }
            $ch = curl_init($url);
            if(!empty($headers)){
                $headerArr = array();
                foreach( $headers as $n => $v ) {
                    $headerArr[] = $n .':' . $v;
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
            $res =  curl_exec($ch);//运行curl
            curl_close($ch);
            return $res;
        }
    }

    if (! function_exists('teambition_user')) {
        function teambition_user($teamId = ''){
            $url = 'https://api.teambition.com/api/organizations/55263514a7d66b384f02e9a1/exportmembers';
            $data = array(
                '_teamId' => $teamId,
            );
            $headers=array(
                'Authorization' => 'OAuth2 XfZIz0sSHlbGOLwqOhC7RRzdQM0=eSBlFAV7cdd94bd5a64664c0c637177b479d3785415e00b0489c362519360e2f6c7337259b1b23098e4f06c8d9df2fc1e52c2f8da843445d3017f93ab6e2ee210b0c1e97a3ab7ea4339161cc68423b6cf390352894820620b850a6c2460391fb161802e1afd1dcd03375607e35d6c0d94ce7f537',
            );
            $ret = teambition_get($url, $data, $headers);
            return _handleUserCSV($ret);
        }
    }

    if (! function_exists('_handleUserCSV')) {

        function _handleUserCSV($ret)
        {
            $header = array(
                'id', 'nike', 'name', 'position', 'staff', 'email', 'phone', 'entryday', 'province', 'city', 'birthday',
            );

            $lines = explode("\n", $ret);

            $count = count($lines);
            if ($count < 2) {
                return array();
            }

            $users = array();
            for ($i = 1; $i < $count; $i++) {
                if (!empty(trim($lines[$i]))) {
                    $users[$i] = _handleArray($header, explode(",", $lines[$i]));
                }
            }

            return $users;
        }
    }

    if (! function_exists('_handleArray')) {

        function _handleArray($header, $val)
        {

            $countHead = count($header);
            $countVal = count($val);

            $rv = array();
            if ($countHead == $countVal) {
                for ($i = 0; $i < $countHead; $i++) {
                    $rv[$header[$i]] = str_replace('"', '', $val[$i]);
                }
            } else if ($countHead < $countVal) {
                $j = 0;
                for ($i = 0; $i < $countHead; $i++) {
                    $rv[$header[$i]] = str_replace('"', '', $val[$i + $j]);
                    $flag = (substr($val[$i + $j], -1) == '"');
                    if (strpos($val[$i + $j], '"') === 0 && !$flag) {
                        for ($k = $i + $j; $k < $countVal; $k++) {
                            $rv[$header[$i]] = $rv[$header[$i]] . "," . str_replace('"', '', $val[$k]);
                            $flag = (substr($val[$k], -1) == '"');
                            if ($flag) {
                                $j = $k - $i;
                                break;
                            }
                        }
                    }
                }
            }
            return $rv;
        }
    }
    if (! function_exists('getTeams')) {

        function getTeams()
        {
            $url = 'https://api.teambition.com/api/organizations/55263514a7d66b384f02e9a1/teams';
            $headers = array(
                'Authorization' => 'OAuth2 XfZIz0sSHlbGOLwqOhC7RRzdQM0=eSBlFAV7cdd94bd5a64664c0c637177b479d3785415e00b0489c362519360e2f6c7337259b1b23098e4f06c8d9df2fc1e52c2f8da843445d3017f93ab6e2ee210b0c1e97a3ab7ea4339161cc68423b6cf390352894820620b850a6c2460391fb161802e1afd1dcd03375607e35d6c0d94ce7f537',
            );
            $ret = teambition_get($url, null, $headers);
            return json_decode($ret, true);
        }
    }

}
